package com.cman777.springc.common.helper;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.Validate;

import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Optional;

/**
 * @author chenzhicong
 * @time 2020/1/15 15:25
 * @description 为了让查询的时候LinkedHashMap whereMap 构造的方便一点
 * 当忽略null值或Blank字符串为查询条件的时候可以用这个类里面的方法链式调用
 */
public class MapBuilder<K, V, L extends Map<K, V>> {
    private L map;

    public MapBuilder(L map) {
        this.map = map;
    }
    public static MapBuilder<String,Object,LinkedHashMap<String,Object>> ofWhereMap() {
        MapBuilder<String,Object,LinkedHashMap<String,Object>>
                mapBuilder = new MapBuilder<>(new LinkedHashMap<>());
        return mapBuilder;
    }

    public MapBuilder<K, V, L> putIfNotBlank(K key, V val) {
        Validate.isTrue(key != null);
        if (val != null && val.getClass().equals(String.class)) {
            if (StringUtils.isBlank((String) val)) {
                return this;
            } else {
                map.put(key, val);
                return this;
            }
        } else {
            Optional.ofNullable(val).ifPresent(v -> map.put(key, val));
            return this;
        }
    }

    public MapBuilder<K, V, L> put(K key, V val) {
        Validate.isTrue(key != null);
        Validate.isTrue(val != null);
        Optional.ofNullable(val).ifPresent(v -> map.put(key, val));
        return this;

    }

    public L getMap() {
        return this.map;
    }

    public LinkedHashMap<K, V> getLinkedHashMap() {
        if (this.map instanceof LinkedHashMap) {
            return (LinkedHashMap<K, V>) this.map;
        } else {
            return new LinkedHashMap<>(map);
        }
    }


}
